using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
using System.ComponentModel;
namespace WroxControls 
{

	// This control renders out three root element HTML elements and thus
	// overrides the Render method
	
   public class MyTextBox : WebControl,
								    IPostBackDataHandler,
									 INamingContainer
   {
		
   	public MyTextBox() : base ("input")
		{
			Context.Trace.Write("MyTextBox","Created");
		}


		//public event EventHandler TextChanged;

		private static readonly object _textChanged = new object();

		public event EventHandler TextChanged 
		{
		   add { Events.AddHandler(_textChanged, value); }
		   remove { Events.RemoveHandler(_textChanged, value); }
		}

		public string Text
      {
         get 
			{
				if ( ViewState["value"] == null )
					return String.Empty;

				
				return (string) ViewState["value"];  
			}
			set
			{
				ViewState["value"] = value;
			}
      }

		protected override void AddAttributesToRender(HtmlTextWriter writer)
		{
				base.AddAttributesToRender(writer);
            writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID);

            writer.AddAttribute(HtmlTextWriterAttribute.Type, "input" );
				if ( Text != null )
					writer.AddAttribute( "value", Text );
				
		}

      bool IPostBackDataHandler.LoadPostData(string postDataKey, NameValueCollection postCollection) 
		{
			bool raiseEvent = false;

			Context.Trace.Write("MyTextBox","Previous value:" + Text);

			if ( Text != postCollection[postDataKey] )
				raiseEvent = true;

			Text = postCollection[postDataKey];

			return raiseEvent;
		}

		void IPostBackDataHandler.RaisePostDataChangedEvent() 
		{
			EventHandler handler = (EventHandler) Events[_textChanged];
         if (handler != null) 
				handler(this, EventArgs.Empty);
		} 

   }
};
